import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import {Form, Icon, Input, Button, Checkbox, message} from 'antd';
import axios from "axios";

class Login extends PureComponent {
  static PropTypes = {
    handleClick: PropTypes.func.isRequired
  }

  state = {
    clientHeight: 0
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        let captchaCode = document.cookie.split('=')[1];
        axios.get('http://localhost:8080/api/login', {
          params: {
            username: values.userName,
            password: values.password
          }
        }).then((res) => {
            if (res.data.code === 200) {
              if (captchaCode.toLowerCase() === values.code.toLowerCase()){
                if (values.remember) {
                  localStorage.setItem('isLogin', true);
                  localStorage.setItem('username', values.userName);
                }else {
                  localStorage.removeItem('isLogin');
                  localStorage.removeItem('user');
                }
                message.success('登录成功');
                window.location.hash = '#/home';
              }else {
                message.error('验证码错误');
                this.editCaptcha();
              }
            }else {
              message.error(res.data.msg);
            }
          })
          .catch((err) => {
            message.error('请求异常，请稍后重试');
          })
      }
    });
  };

  register = () => {
    this.props.handleClick('register');
  };

  forgetPassword = () => {
    this.props.handleClick('forgetPassword');
  };

  editCaptcha = () => {
    this.refs.imgYzm.src = `http://localhost:8080/api/getCaptcha?d=${Math.random()}`
  };

  componentDidMount() {
    if (localStorage.isLogin === 'true') {
      window.location.hash = '#/home';
    }
  }

  render() {
    const { getFieldDecorator } = this.props.form;

    return (
      <Form onSubmit={this.handleSubmit} className="login-form">
        <Form.Item>
          {getFieldDecorator('userName', {
            rules: [{ required: true, message: '请输入用户名' }],
          })(
            <Input style={{height: 40}} prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('password', {
            rules: [{ required: true, message: '请输入密码' }],
          })(
            <Input style={{height: 40}} prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="Password" />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('code', {
            rules: [{ required: true, message: '请输入验证码' }],
          })(
            <Input style={{height: 40, width: '60%'}} type="text" placeholder="验证码" />
          )}
          <img src="http://localhost:8080/api/getCaptcha" alt="验证码" onClick={() => {this.editCaptcha()}} ref="imgYzm"/>
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('remember', {
            valuePropName: 'checked',
            initialValue: true,
          })(
            <Checkbox>记住我</Checkbox>
          )}
          <a href="javascript:;" style={{float: 'right'}} onClick={() => {this.forgetPassword()}}>忘记密码？</a>
          <Button type="primary" htmlType="submit" style={{width: '100%', height: 40}}>
            登录
          </Button>
          Or <a href="javascript:;" onClick={() => {this.register()}}>现在就注册！</a>
        </Form.Item>
      </Form>
    );
  }
}

export default Form.create()(Login);;